<script setup>
import { shortPlayApi } from '@/api/shortPlay'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cloneDeep } from 'lodash-es';

defineExpose({
  showDialog
})
const emit = defineEmits(['getList'])
const props = defineProps({
  shortPlayList: {
    type: Array,
    default: () => []
  }
})
const isShow = ref(false)
const form = ref({
  parentId: '',
  name: ''
})
const rules = ref({
  name: [{ required: true, message: '请输入短剧名称', trigger: 'blur' }]
})
const title = ref('新增短剧')
const formRef = ref()
const sureLoading = ref(false)
const isParentIdDisabled = computed(() => {
  // if(title.value === '新增短剧' && form.value.parentId) {
  //   return true
  // } 
  if(title.value === '编辑短剧' && !form.value.parentId) {
    return true
  }
  return false
})

function showDialog(data, type) {
  isShow.value = true
  if(type == 'add') {
    title.value = '新增短剧'
    console.log('data', data)
    if(data) {
      form.value.parentId = data.id
    } else {
      form.value.parentId = ''
    }
  } else if(type == 'edit') {
    title.value = '编辑短剧'
    form.value = {
      parentId: data.parentId ? data.parentId: '',
      name: data.name,
      id: data.id
    }
  }
}

function handleClose() {
  form.value = {
    parentId: '',
    name: ''
  }
  isShow.value = false
}

function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      sureLoading.value = true
      let params = cloneDeep(form.value)
      if(!params.parentId) {
        params.parentId = 0
      }
      console.log(params)
      if(params.id) {
        shortPlayApi.edit(params).then(res => {
          ElMessage.success('编辑成功')
          handleClose()
          emit('getList')
        }).finally(() => {
          sureLoading.value = false
        })
      } else {
        shortPlayApi.add(params).then(res => {
          ElMessage.success('新增成功')
          handleClose()
          emit('getList')
        }).finally(() => {
          sureLoading.value = false
        })
      }
    }
  })
}
</script>

<template>
  <el-dialog v-model="isShow" :title="title">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="所属上级" prop="parentId">
        <el-select v-model="form.parentId" placeholder="请选择所属上级,不选择则为顶级" :disabled="isParentIdDisabled" clearable>
          <el-option v-for="item,index in props.shortPlayList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="短剧名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入短剧名称" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="sureLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>